package com.wlyuan.open.core.converter.conversions;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wlyuan.open.core.converter.PushMessage;
import lombok.RequiredArgsConstructor;
import lombok.var;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author yuanjie
 */
@RequiredArgsConstructor
public class SimplePushMessageConversion implements PushMessageConversion<PushMessage> {
    private final Map<String, Object> map;
    private final boolean appends;


    private List createArray(JSONArray value, Map<String, Object> map, boolean appends) {
        return value.stream()
                .filter(subValue -> subValue instanceof JSONObject)
                .map(subValue -> createObject((JSONObject) subValue, map, appends))
                .collect(Collectors.toList());
    }

    private JSONObject createObject(JSONObject value, Map<String, Object> map, boolean appends) {
        JSONObject object = appends ? new JSONObject(value) : new JSONObject();
        map.forEach((name, alias) -> {
            if (alias instanceof String) {
                object.put(name, value.get(alias));
            } else if (alias instanceof Map) {
                var subMap = (Map<String, Object>) alias;
                var subValue = value.get(name);
                if (subValue instanceof JSONArray) {
                    object.put(name, createArray((JSONArray) subValue, subMap, appends));
                } else if (subValue instanceof JSONObject) {
                    object.put(name, createObject((JSONObject) subValue, subMap, appends));
                }
            }
        });
        return object;
    }


    @Override
    public Object process(PushMessage source) {
        return createObject((JSONObject) JSON.toJSON(source), map, this.appends);
    }
}
